package io.github.wanggit.antrpc.client.config;

import io.github.wanggit.antrpc.commons.bean.ConfigItem;

import java.util.Iterator;
import java.util.Objects;
import java.util.TreeSet;

/** 从大到小排序 */
class ConfigItemTreeSet extends TreeSet<ConfigItem> {
    private static final long serialVersionUID = -7950132040138456516L;

    ConfigItemTreeSet() {
        super(
                (o1, o2) -> {
                    long value1 = o1.getTs() * o1.getPriority();
                    long value2 = o2.getTs() * o2.getPriority();
                    if (value1 > value2) {
                        return -1;
                    } else if (value1 < value2) {
                        return 1;
                    }
                    return 0;
                });
    }

    void removeAndAddConfigItem(ConfigItem configItem) {
        removeConfigItem(configItem);
        add(configItem);
    }

    void removeConfigItem(ConfigItem configItem) {
        Iterator<ConfigItem> iterator = iterator();
        ConfigItem target = null;
        while (iterator.hasNext()) {
            ConfigItem entity = iterator.next();
            if (Objects.equals(configItem, entity)) {
                target = entity;
                break;
            }
        }
        if (null != target) {
            remove(target);
        }
    }
}
